package com.gmall.batch.gmallbatch.handle.data;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gmall.batch.gmallbatch.model.Message;
import com.gmall.batch.gmallbatch.model.MessageModel;
import com.opencsv.bean.CsvToBeanBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author HL.Wu
 * @date 2020/7/6 16:51
 * <p>
 * for:
 */
@Slf4j
@Component
public class FilePreData {

    @Value("${message.file.path}")
    private String filePath;

    /**
     * 每天定时扫描指定路径下文件 获取响应文件进行读取 解析
     *
     * @return
     */
    public List<Message> preFileData() throws FileNotFoundException {
        // TODO 扫描指定目录下文件
        String file = filePath + DateUtil.today() +".csv";
        if(!new File(file).exists()){
            return null;
        }
        List<Message> list = new CsvToBeanBuilder(new FileReader(new File(file))).withType(Message.class).build().parse();
        // TODO 解析文件内容
        log.info("current parse file info list is \n{}", JSON.toJSONString(list));
        // TODO 转换指定类型数据集合
        return list;
    }

    public List<MessageModel> betFileData(String s){
        List<MessageModel> resList = new ArrayList<>();
        List<Message> list = JSON.parseObject(s,new TypeReference<List<Message>>(){});
        Optional.of(list).ifPresent(mms -> mms.stream().forEach(e -> {
            //  data convert to MessageModel
            MessageModel mm = new MessageModel();
            mm.setMessage(e.getMessage());
            mm.setName(e.getName());
            resList.add(mm);
        }));
        //  转换指定类型数据集合
        return resList;
    }

    public void postFileData(){

        // TODO save data to database or mongodb
    }
}
